package com.company;


import javax.swing.*;
import java.awt.*;

public class CreepingGame {
    private int time = 0;
    public static int antNum = 5;
    public int AntLeft = 5;

    public void setTime(int time) {
        this.time = time;
    }

    public static void setAntNum(int antNum) {
        CreepingGame.antNum = antNum;
    }

    public void setAntLeft(int antLeft) {
        AntLeft = antLeft;
    }

    public CreepingGame(){
        setTime(0);
        setAntNum(5);
        setAntLeft(5);
    }

    public void drivingGame(Ant[] ant) {
        time++;
        for (Ant a : ant) {
            for (Ant b : ant) {
                if (a.getId() < b.getId() && a.getInRange() == 1 && b.getInRange() == 1)
                    detectCollision(a, b);
            }
        }
        for (Ant a : ant) {
            if (a.getInRange() != 0) {
                a.judgeRange();
                if (a.getInRange() == 1)
                    a.creepingOneStep();
                a.judgeRange();
                antLeft(a);
            }
        }
    }

    public void detectCollision(Ant antA, Ant antB) {
        if (Math.abs(antA.getPosition() - antB.getPosition()) <= 5) {
            antA.collision();
            antB.collision();
        }
    }

    public void playGame(Ant[] ant) {
        while (!isOver()) {
            drivingGame(ant);
            Gui.jf.repaint();
            JPanel p1 = new JPanel() {
                @Override
                public void paint(Graphics g) {
                    g.drawRect(50, 400, 900, 10);
                    g.setColor(Color.red);
                    g.fillOval(50 + ant[0].getPosition() * 3, 400, 10, 10);
                    g.setColor(Color.ORANGE);
                    g.fillOval(50 + ant[1].getPosition() * 3, 400, 10, 10);
                    g.setColor(Color.blue);
                    g.fillOval(50 + ant[2].getPosition() * 3, 400, 10, 10);
                    g.setColor(Color.magenta);
                    g.fillOval(50 + ant[3].getPosition() * 3, 400, 10, 10);
                    g.setColor(Color.black);
                    g.fillOval(50 + ant[4].getPosition() * 3, 400, 10, 10);
                }
            };
            Gui.jf.add(p1);
            Gui.jf.setVisible(true);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Gui.jf.remove(p1);


        }
    }

    public void antLeft(Ant ant) {
        if (ant.getInRange() == 0) {
            AntLeft--;
            ant.setLeftTime(time);
        }
    }

    public boolean isOver() {
        return AntLeft == 0;
    }
}
